param (
    [string]$action = ""
)

$services = @(
    @{ Name = "user"; Command = "go run ./apps/user/rpc/user.go" }
)

function Start-Services {
    New-Item -ItemType Directory -Force -Path "logs", "pids" | Out-Null
    foreach ($service in $services) {
        Write-Host "Starting $($service.Name)..."
        $process = Start-Process -NoNewWindow -FilePath "go" -ArgumentList "run $($service.Command.Split()[1])" -PassThru
        $process.Id | Out-File -FilePath "pids\$($service.Name).pid"
        Write-Host "$($service.Name) started (PID: $($process.Id))"
    }
}

function Stop-Services {
    foreach ($pidFile in (Get-ChildItem "pids\*.pid")) {
        $name = $pidFile.BaseName
        $pid = Get-Content $pidFile.FullName
        Write-Host "Stopping $name (PID: $pid)..."
        Stop-Process -Id $pid -ErrorAction SilentlyContinue
        Remove-Item $pidFile.FullName
    }
}

switch ($action) {
    "start" { Start-Services }
    "stop" { Stop-Services }
    "restart" { Stop-Services; Start-Services }
    default { Write-Host "Usage: .\start_all.ps1 {start|stop|restart}" }
}